package servlet;

import entity.Student;
import service.StudentService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet(name = "AddStudentServlet",urlPatterns = "/addstudent")
public class AddStudentServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        // 1.获取请求中的用户名和密码信息并打印出来
        String sid = request.getParameter("sid");
        System.out.println("获取到的学号为：" + sid);
        String sname = request.getParameter("sname");
        System.out.println("获取到的姓名为：" + sname);
        String sex = request.getParameter("sex");
        System.out.println("获取到的性别为：" + sex);
        String birth = request.getParameter("birthday");
        Date birthday = null;
        try {
            birthday = new SimpleDateFormat("yyyy-MM-dd").parse(birth);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        System.out.println("获取到的出生日期为：" + birthday);
        String email = request.getParameter("email");
        System.out.println("获取到的邮箱为：" + email);
        String remarks = request.getParameter("remarks");
        System.out.println("获取到的备注为：" + remarks);

        StudentService studentService = new StudentService();
        if (studentService.ishaveService(sid)){
            System.out.println("添加失败.该学号已经存在");
            request.getSession().setAttribute("message","添加失败，该学号已经有人使用");
            response.sendRedirect("students");
        }else {
            Student student = new Student(sid,sname,sex,birthday,email,remarks);
            studentService.insertStudentService(student);
            System.out.println("添加成功");
            request.getSession().setAttribute("message","添加成功");
            response.sendRedirect("students");
        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
